using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.CmsDbContext
{
    /// <summary>
    /// 低代码数据库上下文工厂
    /// 用于Entity Framework Core设计时创建数据库上下文，支持迁移和工具操作
    /// </summary>
    public class LowCodeDbContextFactory : IDesignTimeDbContextFactory<LowCodeDbContext>
    {
        /// <summary>
        /// 创建数据库上下文实例
        /// 根据配置文件中的数据库类型和连接字符串创建相应的数据库上下文
        /// </summary>
        /// <param name="args">命令行参数</param>
        /// <returns>配置好的数据库上下文实例</returns>
        public LowCodeDbContext CreateDbContext(string[] args)
        {
            var config = new ConfigurationBuilder()
                .SetBasePath(AppContext.BaseDirectory)
                .AddJsonFile("appsettings.json", optional: true)
                .Build();

            var dbType = config["DatabaseType"] ?? "Sqlite";
            var connStr = config.GetConnectionString(dbType) ?? "Data Source=lowcode.db";

            var optionsBuilder = new DbContextOptionsBuilder<LowCodeDbContext>();
            DatabaseOptionsBuilderHelper.ConfigureOptions(optionsBuilder, dbType, connStr);
            return new LowCodeDbContext(optionsBuilder.Options);
        }
    }
}